import sys
import socket
import select

# 创建一个UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 设置客户端的地址和端口
client_address = ("localhost", 10001)
sock.bind(client_address)

# 设置服务器的地址和端口
server_address = ("localhost", 10000)

# 向服务器发送数据
message = "Hello, UDP Echo !".encode()
sock.sendto(message, server_address)

# 初始化等待服务器套接字的列表
inputs = [sock, sys.stdin]

while True:
    # 使用select()等待套接字输入
    readable, _, _ = select.select(inputs, [], [])

    # 遍历所有可读的套接字
    for s in readable:
        if s == sock:
            # 如果是客户端套接字，则接收服务器数据
            data, addr = sock.recvfrom(4096)
            print(f"recv: {addr}, data: {data}")
        elif s == sys.stdin:
            buf = sys.stdin.readline().strip()
            if buf == "q":
                break
            print(f"input: {buf}")
            sock.sendto(buf.encode(), server_address)
        else:
            print("服务器已断开连接")
            inputs.remove(s)
            break
